using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FPMovements : MonoBehaviour
{
    private Transform characterTransform;
    private Rigidbody characterRigidbody;
    public float Speed;
    private bool bIsGrounded = false;
    public float Gravity = 9.8f;
    public float JumpHeight = 1.0f;

    private bool bIsJump;
    void Start()
    {
        characterTransform = transform;
        characterRigidbody = GetComponent<Rigidbody>();
    }

    private void Update()
    {
        if(Input.GetButtonDown("Jump"))
        {
            bIsJump = true;
        }
    }

    void FixedUpdate()
    {
        if(bIsGrounded)
        {
            var m_Horizontal = Input.GetAxis("Horizontal");
            var m_Vertical = Input.GetAxis("Vertical");

            var m_CurrentDirection = new Vector3(m_Horizontal, 0, m_Vertical);
            m_CurrentDirection = characterTransform.TransformDirection(m_CurrentDirection);
            m_CurrentDirection *= Speed;

            var m_CurrentVelocity = characterRigidbody.velocity;

            var m_VelocityChange = m_CurrentDirection - m_CurrentVelocity;

            m_VelocityChange.y = 0;

            characterRigidbody.AddForce(m_VelocityChange, ForceMode.VelocityChange);

            if(bIsJump)
            {
                bIsJump = false;
                characterRigidbody.velocity = new Vector3(m_CurrentVelocity.x, CalculateJumpHeightSpeed(), m_CurrentVelocity.z);
            }
        }

        characterRigidbody.AddForce(new Vector3(0, -Gravity * characterRigidbody.mass, 0));
    }

    private float CalculateJumpHeightSpeed()
    {
        return Mathf.Sqrt(2 * Gravity * JumpHeight);
    }

    private void OnCollisionStay(Collision collision)
    {
        bIsGrounded = true;
    }

    private void OnCollisionExit(Collision collision)
    {
        bIsGrounded = false;
    }
}
